package com.chrudgames.stayintouch;



import com.chrudgames.stayintouch.R;
import com.chrudgames.stayintouch.Consts;
import com.chrudgames.stayintouch.BillingService;
import com.chrudgames.stayintouch.Consts.PurchaseState;
import com.chrudgames.stayintouch.Consts.ResponseCode;
import com.chrudgames.stayintouch.PurchaseObserver;
import com.chrudgames.stayintouch.ResponseHandler;
import com.chrudgames.stayintouch.BillingService.RequestPurchase;
import com.chrudgames.stayintouch.BillingService.RestoreTransactions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;



public class Upgrade extends Activity implements OnClickListener {
	
    DatabaseHandler db = new DatabaseHandler(this);
    boolean bolOwned;
       
    
	private SitPurchaseObserver mPurchaseObserver;
    private Handler mHandler;
    //private PurchaseDatabase mPurchaseDatabase;
  //  private TextView mLogTextView;
    private BillingService mBillingService;
    private static final String TAG = "StayInTouch";
	/** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upgrade);
        
        bolOwned=false;
        
       
        mHandler = new Handler();
        mPurchaseObserver = new SitPurchaseObserver(mHandler);
        mBillingService = new BillingService();
        mBillingService.setContext(this);


        // Check if billing is supported.
        ResponseHandler.register(mPurchaseObserver);
        if (!mBillingService.checkBillingSupported()) {
        	
        }else{
        	mBillingService.restoreTransactions();
        	
        }
    
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        	mBillingService.unbind();
        	
        }//end onDestroy()

    
    private class SitPurchaseObserver extends PurchaseObserver {
        public SitPurchaseObserver(Handler handler) {
            super(Upgrade.this, handler);
        }

        @Override
        public void onBillingSupported(boolean supported) {
            if (Consts.DEBUG) {

            }
            if (supported) {
                //restoreDatabase();
               // mBuyButton.setEnabled(true);
              } else {
              //  showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
            }
        }

        @Override
        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) {
        	
        	logProductActivity(TAG, "onPurchaseStateChange  " + itemId);
        	
            if (Consts.DEBUG) {
             
            }

            if (developerPayload == null) {
                logProductActivity(itemId, purchaseState.toString());
            } else {
                logProductActivity(itemId, purchaseState + "\n\t" + developerPayload);
            }

            if (purchaseState == PurchaseState.PURCHASED) {
            	
            	bolOwned=true;
            	
            	TextView mTextView = (TextView) findViewById(R.id.tvMessage);
            	mTextView.setText(getString(R.string.You_are_running_the_full_version));
            	
            	Button b = (Button) findViewById(R.id.upgradebutton);
            	b.setText("Back");
            	b.setEnabled(true);
            	            	           	
         	    alertbox("StayInTouch",getString(R.string.StayInTouch_is_now));
         	    	
            	
            }
            //mCatalogAdapter.setOwnedItems(mOwnedItems);
            //mOwnedItemsCursor.requery();
        }

        @Override
        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {
        	
        	logProductActivity(TAG, "onRequestPurchaseResponse " + responseCode);
        	
        
            if (responseCode == ResponseCode.RESULT_OK) {
              
                logProductActivity(request.mProductId, "sending purchase request");
            } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
                
                logProductActivity(request.mProductId, "dismissed purchase dialog");
            } else {
               
                logProductActivity(request.mProductId, "request purchase returned " + responseCode);
            }
        }

        @Override
        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
        	
        	logProductActivity(TAG, "restore purchase code " + responseCode);
        	
            if (responseCode == ResponseCode.RESULT_OK) {
            	
            	TextView mTextView = (TextView) findViewById(R.id.tvMessage);
            	mTextView.setText(getString(R.string.You_are_running_the_Free_version));
            	
            	Button b = (Button) findViewById(R.id.upgradebutton);
            	b.setText(getString(R.string.Pricing));
            	b.setEnabled(true);
            	
            } else {
            	
            	alertbox("StayInTouch", getString(R.string.There_was_a_problem));
            	
            	TextView mTextView = (TextView) findViewById(R.id.tvMessage);
            	mTextView.setText("Problem: " + responseCode.toString());
            	
            	Button b = (Button) findViewById(R.id.upgradebutton);
            	b.setText("Try Later");
            	
            }
        }
    }
    

    private void prependLogEntry(CharSequence cs) {
        SpannableStringBuilder contents = new SpannableStringBuilder(cs);
        contents.append('\n');
       // contents.append(mLogTextView.getText());
      //  mLogTextView.setText(contents);
    }

    private void logProductActivity(String product, String activity) {
        SpannableStringBuilder contents = new SpannableStringBuilder();
        contents.append(Html.fromHtml("<b>" + product + "</b>: "));
        contents.append(activity);
        prependLogEntry(contents);
    }

    /**
     * If the database has not been initialized, we send a
     * RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items
     * for this user. This happens if the application has just been installed
     * or the user wiped data. We do not want to do this on every startup, rather, we want to do
     * only when the database needs to be initialized.
     */
    /*
    private void restoreDatabase() {
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        boolean initialized = prefs.getBoolean(DB_INITIALIZED, false);
        if (!initialized) {
            mBillingService.restoreTransactions();
            Toast.makeText(this, "Restoring Transactions", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Creates a background thread that reads the database and initializes the
     * set of owned items.
     */
    /*
    private void initializeOwnedItems() {
        new Thread(new Runnable() {
            public void run() {
                doInitializeOwnedItems();
            }
        }).start();
    }
    */
    
  
    
    /**
     * Reads the set of purchased items from the database in a background thread
     * and then adds those items to the set of owned items in the main UI
     * thread.
     */
    /*
    
    private void doInitializeOwnedItems() {
        Cursor cursor = mPurchaseDatabase.queryAllPurchasedItems();
        if (cursor == null) {
            return;
        }

        final Set<String> ownedItems = new HashSet<String>();
        try {
            int productIdCol = cursor.getColumnIndexOrThrow(
                    PurchaseDatabase.PURCHASED_PRODUCT_ID_COL);
            while (cursor.moveToNext()) {
                String productId = cursor.getString(productIdCol);
                ownedItems.add(productId);
            }
        } finally {
            cursor.close();
        }

        // We will add the set of owned items in a new Runnable that runs on
        // the UI thread so that we don't need to synchronize access to
        // mOwnedItems.
        mHandler.post(new Runnable() {
            public void run() {
              //  mOwnedItems.addAll(ownedItems);
               // mCatalogAdapter.setOwnedItems(mOwnedItems);
            }
        });
    }

    */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            
        case R.id.communicate:
        	Intent i4 = new Intent(this, Communicate.class);

        	startActivity(i4);
        	return true;
      	
        case R.id.options:
            	Intent i = new Intent(this, Prefs.class);
               	startActivity(i);
    	
                return true;
            case R.id.upgrade:
            	Intent i3 = new Intent(this, Upgrade.class);
               	startActivity(i3);
                return true;
            case R.id.help:
            	Intent i2 = new Intent(this, Help.class);
               	startActivity(i2);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    
 public void onClick(View v) {
    	
    	switch (v.getId()) {
    	
    	case R.id.upgradebutton:

    		if (bolOwned) {
    			
    			this.finish();
    			
    		}else{
    		
    			if (!mBillingService.requestPurchase("001", null)) {
                //showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
    			}
          	
    		}
            
           	break;
        	
    	}
          	
           
          
        }


 protected void alertbox(String title, String mymessage)
 {
 new AlertDialog.Builder(this)
    .setMessage(mymessage)
    .setTitle(title)
    .setCancelable(true)
    .setNeutralButton(android.R.string.ok,
       new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int whichButton){}
       })
    .show();
 }
    
}
	
